package org.example.seckill.util;

import org.example.seckill.bean.User;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author woopsion
 * @date 2025-07-02
 */
public class SessionRegisterRedis {
    // 数据库配置
    private static final String DB_URL = "jdbc:mysql://192.168.5.6:3306/seckill";
    private static final String DB_USER = "woopsion";
    private static final String DB_PASSWORD = "hsp8";
    // 登录接口配置
    private static final String LOGIN_URL = "http://localhost:8080/login/doLogin";
    private static final String OUTPUT_FILE = "D:\\DeskTop\\user_tickets.txt";


    public static void main(String[] args) {
        List<User> users = getUsersFromDatabase();
        if (users.isEmpty()) {
            System.out.println("未找到用户数据");
            return;
        }

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE))) {
            for (User user : users) {
                String userTicket = loginAndGetTicket(user);
                if (userTicket != null) {
                    String line = user.getId() + "," + userTicket;
                    writer.write(line);
                    writer.newLine();
                    System.out.println("成功获取用户 " + user.getId() + " 的ticket");
                } else {
                    System.out.println("用户 " + user.getId() + " 登录失败");
                }
            }
            System.out.println("结果已保存至: " + OUTPUT_FILE);
        } catch (IOException e) {
            System.err.println("文件写入错误: " + e.getMessage());
        }
    }

    

    private static List<User> getUsersFromDatabase() {
        List<User> users = new ArrayList<>();
        String sql = "SELECT id, password FROM seckill_user";

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            while (rs.next()) {
                User user = new User();
                user.setId(rs.getLong("id"));
                user.setPassword(rs.getString("password"));
                users.add(user);
            }
        } catch (SQLException e) {
            System.err.println("数据库错误: " + e.getMessage());
        }
        return users;
    }

    private static String loginAndGetTicket(User user) {
        try {
            URL url = new URL(LOGIN_URL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置请求参数
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 构建请求体
            String postData = "mobile=" + user.getId() + "&password=123456" ;
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = postData.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 从响应头获取Cookie
                String cookies = conn.getHeaderField("Set-Cookie");
                if (cookies != null) {
                    return extractUserTicket(cookies);
                }
            } else {
                System.err.println("登录失败 - HTTP代码: " + responseCode + " 用户: " + user.getId());
            }
        } catch (Exception e) {
            System.err.println("请求错误: " + e.getMessage() + " 用户: " + user.getId());
        }
        return null;
    }

    private static String extractUserTicket(String cookieHeader) {
        String[] cookies = cookieHeader.split(";");
        for (String cookie : cookies) {
            if (cookie.trim().startsWith("userTicket=")) {
                return cookie.substring("userTicket=".length()).trim();
            }
        }
        return null;
    }

}

